/*
 * Copyright (C) 2006 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.moxiu.browser;

import java.util.ArrayList;
import java.util.List;

import com.moxiu.browser.preferences.BrowserAlcPost;
import com.moxiu.browser.menu.DesktopMenuAdapter;
import com.moxiu.browser.stub.NullController;
import com.moxiu.browser.view.DesktopMenuGridView;
import com.moxiu.launcher.LauncherApplication;
import com.moxiu.launcher.R;
import com.moxiu.launcher.config.StaticMethod;
import com.qq.e.ads.cfg.MultiProcessFlag;
import com.qq.e.ads.nativ.NativeAD;
import com.qq.e.ads.nativ.NativeADDataRef;
import com.qq.e.ads.nativ.NativeAD.NativeAdListener;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.PowerManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.OvershootInterpolator;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;

public class BrowserActivity extends Activity { 

    public static final String ACTION_SHOW_BOOKMARKS = "show_bookmarks";
    public static final String ACTION_SHOW_BROWSER = "show_browser";
    public static final String ACTION_RESTART = "--restart--";
    private static final String EXTRA_STATE = "state";
    public static final String EXTRA_DISABLE_URL_OVERRIDE = "disable_url_override";

    public static final String FROM_TAG = "from_tag";
    
    public static final int FROM_UNKNOWN = -1;
    
    public static final int FROM_LAUNCHER = 0;
    public static final int FROM_MOXIU_INNER_URL = 1;
    
    private final static String LOGTAG = "browser";

    private final static boolean LOGV_ENABLED =  LauncherApplication.LOGV_ENABLED;

    private ActivityController mController = NullController.INSTANCE;

    private int mComeFrom = FROM_UNKNOWN;
    public String mComeFromTag = "";
    private BrowserAlcPost browserAlcPost;
    private static boolean isCreate = true;
    
    @Override
    public void onCreate(Bundle icicle) {
        if (LOGV_ENABLED) {
            Log.v(LOGTAG, this + " onStart, has state: "
                    + (icicle == null ? "false" : "true"));
        }
        browserAlcPost = new BrowserAlcPost(getApplicationContext());
        browserAlcPost.setBrowserData(BrowserAlcPost.IS_HOME, browserAlcPost.getIsHome(false));
        BrowserAlcPost.SlideDownSend = false;
        super.onCreate(icicle);
 		initFromWhere(getIntent());
initH5GDT(this, 30);
        if (!supportSDK()) {
        	finish();
        	return;
        }
        
        
        // If this was a web search request, pass it on to the default web
        // search provider and finish this activity.
        if (IntentHandler.handleWebSearchIntent(this, null, getIntent())) {
            finish();
            return;
        }
        mController = createController();
        Intent intent = (icicle == null) ? getIntent() : null;
        mController.start(intent);
    }

	/**
	 * @return the ads
	 */
	public List<NativeADDataRef> getAds() {
		return ads;
	}

	/**
	 * @param ads
	 *            the ads to set
	 */
	public void setAds(List<NativeADDataRef> ads) {
		this.ads = ads;
	}

	public List<NativeADDataRef> ads = null;
	private NativeAD gdtnativead2;

	public void initH5GDT(Context mContext, int count) {
		try {
			if (!"GT-I9152".equals(android.os.Build.MODEL)) {
				if (!StaticMethod.iscloseGuangDainByChild(mContext)) {
					initGDTNativeAd2();
					loadAd2(count);
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static final String I_POS_ID = "3000207764796345"; // 聚合搜索banner
	private static final String MXAPPID = "221632";

	public void initGDTNativeAd2() {
		ads = new ArrayList<NativeADDataRef>();
		try {
			MultiProcessFlag.setMultiProcess(true);
			gdtnativead2 = new NativeAD(this, MXAPPID, I_POS_ID,
					new NativeAdListener() {

						@Override
						public void onADLoaded(List<NativeADDataRef> refs) {

							if (refs != null && refs.size() > 0) {
								for (NativeADDataRef nativeADDataRef : refs) {
									if(nativeADDataRef.isAPP()){
										ads.add(nativeADDataRef);
										continue;
									}
								}
//								ads = refs;
								 
							}

						}

						@Override
						public void onNoAD(int errorCode) {
						}

						@Override
						public void onADStatusChanged(NativeADDataRef ref) {

						}
					});

		} catch (Exception e) {
		}
	}

	protected void loadAd2(int count) {
		// count = count == 0 ? 5 : count;
		if (count >= 30) {
			count = 30;
		}
		// 一次拉取的广告条数：范围1-30
		try {

			gdtnativead2.loadAD(count);

		} catch (Exception e) {
		}
	}

	private void initFromWhere(Intent intent) {
		if (intent == null) {
			mComeFrom = FROM_UNKNOWN;
			return;
		}

    	String action = intent.getAction();
    	mComeFromTag = intent.getStringExtra(FROM_TAG);
    	browserAlcPost.clearOneData(BrowserAlcPost.REFERER);
    	browserAlcPost.setBrowserData(browserAlcPost.REFERER, browserAlcPost.getReferer(mComeFromTag));
    	if (Intent.ACTION_MAIN.equals(action)) {
    		mComeFrom = FROM_LAUNCHER;
    		mComeFromTag = "from_launcher";
    		browserAlcPost.setBrowserData(browserAlcPost.REFERER, browserAlcPost.getReferer(mComeFromTag));
    		return;
    	}
    	
    	if (TextUtils.isEmpty(mComeFromTag)) {
    		mComeFrom = FROM_UNKNOWN;
    	} else  {
    		mComeFrom = FROM_MOXIU_INNER_URL;
    	}
    }
    
    public int getFromWhere() {
    	return mComeFrom;
    }
    
    public String getFromTag() {
    	return mComeFromTag;
    }
    
    public static boolean isTablet(Context context) {
        return context.getResources().getBoolean(R.bool.isTablet);
    }
    private boolean supportSDK() {
    	if (BrowserSettings.isSupportThisMobile()) {
    		return true;
    	} else {
    		Toast.makeText(this.getApplicationContext(), "本浏览器不支持Android 4.0 以下的手机", Toast.LENGTH_LONG).show();
    		return false;
    	}
    }
    private Controller createController() {
        Controller controller = new Controller(this);
        boolean xlarge = isTablet(this);
        UI ui = null;
//        if (xlarge) {
//            ui = new XLargeUi(this, controller);
//        } else {
            ui = new PhoneUi(this, controller);
//        }
        controller.setUi(ui);

        return controller;
    }

//    @VisibleForTesting
    Controller getController() {
        return (Controller) mController;
    }

    @Override
    protected void onNewIntent(Intent intent) {
//        if (shouldIgnoreIntents()) return;
        initFromWhere(intent);
        
        if (ACTION_RESTART.equals(intent.getAction())) {
            Bundle outState = new Bundle();
            mController.onSaveInstanceState(outState);
            finish();
            getApplicationContext().startActivity(
                    new Intent(getApplicationContext(), BrowserActivity.class)
                    .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    .putExtra(EXTRA_STATE, outState));
            return;
        }
        browserAlcPost.clearAlcData();
        browserAlcPost.setBrowserData(BrowserAlcPost.ACT_TYPE, BrowserAlcPost.B_BROWSE);
       BrowserAlcPost.homeStateChanged = 0;
        BrowserAlcPost.isNewIntent = true;
        
    	isCreate = true;
        
        mController.handleNewIntent(intent);
    }

    private KeyguardManager mKeyguardManager;
    private PowerManager mPowerManager;
    private boolean shouldIgnoreIntents() {
        // Only process intents if the screen is on and the device is unlocked
        // aka, if we will be user-visible
        if (mKeyguardManager == null) {
            mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        }
        if (mPowerManager == null) {
            mPowerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        }
        
        
        boolean ignore = !mPowerManager.isScreenOn();
        
       
        
        ignore |= mKeyguardManager.inKeyguardRestrictedInputMode();
        
        if (LOGV_ENABLED) { 
            Log.v(LOGTAG, "ignore intents: " + ignore);
        }
        return ignore;
    }

    @Override
    protected void onResume() {
        super.onResume();
//        browserAlcPost.isPreRunning = false;
////        initFromWhere(getIntent());
//        if (!isCreate && !browserAlcPost.isPreRunning) {
//        	browserAlcPost.setBrowserData(browserAlcPost.POSITION, browserAlcPost.PRE_POSITION);
//        	
//        	browserAlcPost.postAlcData(getApplicationContext());
//		}
        if (LOGV_ENABLED) {
            Log.v(LOGTAG, "BrowserActivity.onResume: this=" + this);
        }
        mController.onResume();
        
       
    }
    
    @Override
    public void setRequestedOrientation(int requestedOrientation) {
//    	if (((UiController)mController).getHomePage().isShowing()) {
//    		
//    		super.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//    	} else {
    	
    		super.setRequestedOrientation(requestedOrientation);
//    	}
    }

//    @Override
//    public boolean onMenuOpened(int featureId, Menu menu) {
//        if (Window.FEATURE_OPTIONS_PANEL == featureId) {
//        	Log.i("kevint", "BrowserActivity========onMenuOpened");
//            mController.onMenuOpened(featureId, menu);
//        }
//        return true;
//    }
//
//    @Override
//    public void onOptionsMenuClosed(Menu menu) {
//    	Log.i("kevint", "BrowserActivity========onOptionsMenuClosed");
//        mController.onOptionsMenuClosed(menu);
//    }
//
//    @Override
//    public void onContextMenuClosed(Menu menu) {
//        super.onContextMenuClosed(menu);
//        Log.i("kevint", "BrowserActivity========onContextMenuClosed");
//        mController.onContextMenuClosed(menu);
//    }

    /**
     *  onSaveInstanceState(Bundle map)
     *  onSaveInstanceState is called right before onStop(). The map contains
     *  the saved state.
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (LOGV_ENABLED) {
            Log.v(LOGTAG, "BrowserActivity.onSaveInstanceState: this=" + this);
        }
        mController.onSaveInstanceState(outState);
    }

    @Override
    protected void onPause() {
        mController.onPause();
        Log.d("running", "后台运行啦");
//        if (!browserAlcPost.isPreRunning) {
//        	browserAlcPost.clearAlcData();
//        	browserAlcPost.setBrowserData(browserAlcPost.POSITION, browserAlcPost.BACK_POSITION);
//        	browserAlcPost.postAlcData(getApplicationContext());
//        	isCreate = false;
//        	Log.d("running", "### " + browserAlcPost.isPreRunning);
//		}
//        browserAlcPost.isPreRunning = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (LOGV_ENABLED) {
            Log.v(LOGTAG, "BrowserActivity.onDestroy: this=" + this);
        }
        browserAlcPost.sendBrowseMessage(false, false);
        super.onDestroy();
        mController.onDestroy();
        mController = NullController.INSTANCE;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mController.onConfgurationChanged(newConfig);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mController.onLowMemory();
    }

//    @Override
//    public boolean onCreateOptionsMenu(Menu menu) {
//        super.onCreateOptionsMenu(menu);
//        return mController.onCreateOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onPrepareOptionsMenu(Menu menu) {
//        super.onPrepareOptionsMenu(menu);
//        return mController.onPrepareOptionsMenu(menu);
//    }
//
//    @Override
//    public boolean onOptionsItemSelected(MenuItem item) {
//        if (!mController.onOptionsItemSelected(item)) {
//            return super.onOptionsItemSelected(item);
//        }
//        return true;
//    }
//
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) {
        mController.onCreateContextMenu(menu, v, menuInfo);
    }
//
//    @Override
//    public boolean onContextItemSelected(MenuItem item) {
//        return mController.onContextItemSelected(item);
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//    	if (isMenuShowing()) {
//    		return true;
//    	}
//    	
//    	boolean isDeal = mController.onKeyDown(keyCode, event);
//    	boolean superDeal =  false;
//    	if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//    		Log.i("kevint", "BrowserActivity===========KEYCODE_BACK==onKeyDown=isDeal="+isDeal+",superDeal="+superDeal);
//    		if (!isDeal) {
//        		return true;
//        	}
//    	}
//    	
//    	
//        return isDeal ||
//        		super.onKeyDown(keyCode, event);
        return mController.onKeyDown(keyCode, event) ||
            super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyLongPress(int keyCode, KeyEvent event) {
        return mController.onKeyLongPress(keyCode, event) ||
            super.onKeyLongPress(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
    	
//    	if (isMenuShowing()) {
//    		menuColoseAnim(true);
//    		return true;
//    	}
    	
//    	if (mParentActivity != null && mParentActivity.isMenuShowing()) {
//    		mParentActivity.onKeyDown(keyCode, event);
//    		return false;
//    	}
//    	
//    	Log.d("kevint", "BrowserActivity===========keyCode == KeyEvent.KEYCODE_BACK="+(keyCode == KeyEvent.KEYCODE_BACK));
//    	boolean isDeal = mController.onKeyUp(keyCode, event);
//    	
//    	boolean superDeal = false;
//    	
//    	if ((keyCode == KeyEvent.KEYCODE_BACK)) {
//    		Log.d("kevint", "BrowserActivity===========KEYCODE_BACK==onKeyUp=isDeal="+isDeal +",superDeal="+superDeal +", mParentActivity="+mParentActivity);
//    		if (!isDeal && mParentActivity != null) {
//        		mParentActivity.onActivityDestroyAsKeyBack(this);
//        		return false;
//        	}
//    	}
//    	
//    	
//    	
//        return  isDeal ||
//        		super.onKeyUp(keyCode, event);
        
        return mController.onKeyUp(keyCode, event) ||
            super.onKeyUp(keyCode, event);
    }

    @Override
    public void onActionModeStarted(ActionMode mode) {
        super.onActionModeStarted(mode);
        mController.onActionModeStarted(mode);
    }

    @Override
    public void onActionModeFinished(ActionMode mode) {
        super.onActionModeFinished(mode);
        mController.onActionModeFinished(mode);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent intent) {
        mController.onActivityResult(requestCode, resultCode, intent);
    }

    @Override
    public boolean onSearchRequested() {
        return mController.onSearchRequested();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
      	
        return mController.dispatchKeyEvent(event)
                || super.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
    	
        return mController.dispatchKeyShortcutEvent(event)
                || super.dispatchKeyShortcutEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
    	
        return mController.dispatchTouchEvent(ev)
                || super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean dispatchTrackballEvent(MotionEvent ev) {
    	
        return mController.dispatchTrackballEvent(ev)
                || super.dispatchTrackballEvent(ev);
    }

    @Override
    public boolean dispatchGenericMotionEvent(MotionEvent ev) {
  
        return mController.dispatchGenericMotionEvent(ev) ||
                super.dispatchGenericMotionEvent(ev);
    }
    
    
   
    

}
